const app = getApp();
var cache = require('../../../utils/cache.js');
var imgshow = false;
Page({
  data: {
    tabbar: 1,
    active: 0,
    state: 0, fy: { page: 1, count: 0, end: 1 }//分页
  },
  onLoad: function (options) {
    this.setData({ user: wx.getStorageSync('userinfo'), uid: parseInt(wx.getStorageSync('FXID')),cid :options.cid });   
    this.get_lists();
  },
  onShow: function () {
    if (app.reg() && !imgshow) {
      
    }
  },
  get_lists: function () {
    if (!this.data.fy.end) return false;
    var data = {};
    if (this.data.state == 2) {
      data = { state: this.data.state, la: this.data.location.la, lg: this.data.location.lg, cid: this.data.cid, page: this.data.fy.page, total: this.data.fy.count };
    } else {
      data = { state: this.data.state, cid: this.data.cid, page: this.data.fy.page, total: this.data.fy.count };
    }
    wx.showLoading({ title: '玩命加载中', mask: true });
    wx.request({
      url: app.globalData.host + 'wechat/api/tie',
      data: data,
      method: 'POST',
      header: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
      success: d => {
        if (d.data.state == 1) {
          this.data.fy = d.data.mark;
          this.setData({ tie_lists: this.data.tie_lists ? this.data.tie_lists.concat(d.data.data) : d.data.data });
        } else {
          this.data.fy.end = 0;
          this.setData({ tie_lists: '', msg: d.data.message });
        }
        wx.hideLoading();
      }
    })
  },
  onImg: function (e) {
    imgshow = true;
    wx.previewImage({
      current: e.currentTarget.dataset.src,
      urls: e.currentTarget.dataset.total,
      complete: function () {

      }
    })
  },
  onDianpin: function (e) {
    this.setData({ dianpin: e.currentTarget.id, dianpinbg: true });
    this.setData({ dianpinbg: true });
  },
  onHidedianpian: function () {
    this.setData({ dianpin: '', dianpinbg: false });
  },
  onZan: function (e) {
    wx.showLoading({ title: '点赞中...', mask: true });
    var key = e.currentTarget.dataset.key;
    var tielists = "tie_lists[" + key + "].zan";
    wx.request({
      url: app.globalData.host + 'wechat/api/zan',
      data: { tid: this.data.tie_lists[key].id, uid: this.data.uid, header: this.data.user.avatarUrl, nickname: this.data.user.nickName },
      method: 'POST',
      header: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
      success: d => {
        if (d.data.state == 1) {
          this.data.tie_lists[key].zan.push({ uid: this.data.uid, h: this.data.user.avatarUrl });
          this.setData({ dianpin: '', dianpinbg: false, [tielists]: this.data.tie_lists[key].zan });
        } else {
          wx.showToast({
            title: d.data.message, icon: 'none'
          })
        }
        wx.hideLoading();
      }
    })
  },
  onZandel: function (e) {
    wx.showLoading({ title: '取消中...', mask: true });
    var key = e.currentTarget.dataset.key, uid = this.data.uid;
    var tielists = "tie_lists[" + key + "].zan";
    wx.request({
      url: app.globalData.host + 'wechat/api/zan_del',
      data: { tid: this.data.tie_lists[key].id, uid: this.data.uid },
      method: 'POST',
      header: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
      success: d => {
        if (d.data.state == 1) {
          var newslists = this.data.tie_lists[key].zan.filter(function (item) {
            return item.uid != uid;
          });
          this.setData({ dianpin: '', dianpinbg: false, [tielists]: newslists.length ? newslists : [] });
        } else {
          wx.showToast({
            title: d.data.message, icon: 'none'
          })
        }
        wx.hideLoading();
      }
    })

  },
  onPinlun: function (e) {
    this.setData({ dianpin: '', dianpinbg: false, showpopup: true, plinput: true, commentid: e.currentTarget.id });
  },
  onClosepop: function () {
    this.setData({ showpopup: false })
  },
  onCommentsub: function (e) {
    wx.showLoading({ title: '提交中...', mask: true });
    var con = e.detail;
    var key = this.data.commentid;
    this.data.tie_lists[key].comment.push({ uid: this.data.uid, n: this.data.user.nickName, c: con });
    var tielists = "tie_lists[" + key + "].comment";
    wx.request({
      url: app.globalData.host + 'wechat/api/comment',
      data: { tid: this.data.tie_lists[key].id, uid: this.data.uid, header: this.data.user.avatarUrl, nickname: this.data.user.nickName, content: con },
      method: 'POST',
      header: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest' },
      success: d => {
        if (d.data.state == 1) {
          this.setData({ dianpin: '', dianpinbg: false, showpopup: false, plinput: false, [tielists]: this.data.tie_lists[key].comment, commentVal: '' });
        } else {
          wx.showToast({
            title: d.data.message, icon: 'none'
          })
        }
        wx.hideLoading();
      }
    })

  },
  onMap: function (e) {
    wx.openLocation({
      latitude: parseFloat(e.currentTarget.dataset.la),
      longitude: parseFloat(e.currentTarget.dataset.lg),
      address: e.currentTarget.dataset.name
    })
  },
  onDetail: function (e) {
    var id = e.currentTarget.id
    wx.navigateTo({
      url: '/pages/index/detail/index?id=' + id + "&bottom=" + e.currentTarget.dataset.bottom,
    })
  },
  onTab: function (e) {
    var index = e.detail.index;
    this.setData({ state: index });
    this.resetFy();
    if (index == 2) {//获取附近的信息/
      var location = cache.get('location');
      if (location) {//本地缓存的地址信息    
        console.log(location)
        this.setData({ location });
        this.get_lists();
      } else {//获取最新的地址，并执行获取数据
        this.get_location();
      }
    } else {
      this.get_lists();
    }

  },
  get_location() {
    wx.showLoading({
      title: '位置计算中',
    })
    wx.getLocation({
      success: res => {//正常获取    
        var la = res.latitude, lg = res.longitude;
        cache.put('location', { la: la, lg: lg }, 43200);//存入缓存 过期时间1天
        this.setData({ location: { la: la, lg: lg } });
        this.get_lists();
      },
      fail: res => {//用户拒绝，则提示重新获取
        wx.showModal({
          title: '警告',
          content: '此功能无法使用，请允许使用定位',
          success: res1 => {
            if (res1.confirm) {
              wx.openSetting({
                success: res2 => {
                  if (res2.authSetting["scope.userLocation"]) {//如果用户重新同意了授权登录
                    wx.showToast({ title: '授权成功', duration: 2000 });
                    setTimeout(() => {  //要等2秒 才能收到数据
                      this.get_location();
                    }, 2000);
                  }
                }
              })
            } else {//用户再次拒绝，则获取失败
              this.setData({ tie_lists: '', msg: '无法使用此功能!~~~~(>_<)~~~~' });
            }
          }
        })

      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },
  onReachBottom: function () {
    this.get_lists();
  },
  resetFy: function () {//重置分页
    this.data.fy = { page: 1, count: 0, end: 1 };
    this.data.tie_lists = '';
  }
})